const log = require('../../utils/log');
const gameCfg = require('../../config/gameCfg');
const gameZtCfg = require('./gameZtCfg');
const RoomInfo = require('./roomInfo');
const AlgorZt = require('./algorZt');
const redisBase = require('../../common/RedisBase');

class GameZtModel {
    static getInstance(){
        if(!GameZtModel.instance){
            GameZtModel.instance = new GameZtModel();
            return GameZtModel.instance;
        }else{
            return GameZtModel.instance;
        }
    }

    constructor() {
        this.User = {
            uid: "", //房间里玩家id
            totalTime: 0, //房间里改玩家当前轮消耗的总时间
            totalScore:0, //房间里改玩家当前轮得到的总分数
            isWin: 0, //当前用户输赢状态 0是输了 1是赢了
            sessicon:null, //当前的客户端
        }
        // let answerLen = 0; //记录房间里答题的人数
        //记录房间信息
        this.roomInfo = {};
    }

    getRoomInfo(roomId){
        if(!this.roomInfo[roomId]){
            this.roomInfo[roomId] = new RoomInfo(roomId);
        }
        return this.roomInfo[roomId];
    }


    //更新主题答题总数
    async updateAnswerZtTotal(uid, gameType){
        // return new Promise(async(resolve, reject)=> {
            //获取 gameInfo_list_zt 列表
            let gameList = await redisBase.getGameListZt();
            log.error('=======updateAnswerZtTotal===========',gameList.length);
            for (let i = 0; i < gameList.length; i++) {
                let cfg = JSON.parse(gameList[i]);
                if (cfg.gamType === gameType && cfg.uid === uid) {
                    cfg.countTotal++;
                    let res = await redisBase.updateGameListTzValue(i, JSON.stringify(cfg));
                    if(res){
                        // resolve(res);
                    }else {
                        // reject(null);
                    }
                    break;
                }
            }
            log.info('=======updateAnswerZtTotal end===========');
        // })
    }

    //更新答对的题目数
    async updateAnswerZtTrue(uid, gameType){
        // return new Promise(async(resolve, reject)=>{
            let gameInfoList = await redisBase.getGameListZt();
            if(gameInfoList) {
                for (let i = 0; i < gameInfoList.length; i++) {
                    let cfg = JSON.parse(gameInfoList[i]);
                    if (cfg.gamType === gameType && cfg.uid === uid) {
                        cfg.countWin++;

                        //知识三维图数据
                        let arr = {0:0,1:0,2:1,3:1, 4:2,5:2, 6:3,7:3, 8:4,9:4, 10:5}
                        let ranks = cfg.rankZst;
                        //更新文体的知识答题区域, 目前以自己答得题目计算
                        let idx = Math.floor((cfg.countWin/cfg.countTotal)*10);
                        if(gameType === gameCfg.DWTYPE.DW_WENTI) {
                            ranks[0] = arr[idx];
                        }else if(gameType === gameCfg.DWTYPE.DW_ZUQIU){
                            ranks[1] = arr[idx];
                        }else if(gameType === gameCfg.DWTYPE.DW_MINGZU){
                            ranks[2] = arr[idx];
                        }
                        cfg.rankZst = ranks;

                        log.info('=======更新答对的题目数 start==========')
                        let res = await redisBase.updateGameListTzValue(i, JSON.stringify(cfg));
                        if(res){
                            log.info('=======更新答对的题目数 end1==========',res)
                            // resolve(cfg);
                        }else {
                            // reject(null);
                        }
                        log.info('=======更新答对的题目数 end2==========')
                        break;
                    }
                }
            }
        log.info('=======更新答对的题目数 end3==========')
        // })
    }

    //更新用户的分数
    updateUserScore(uid,gameType, score){
        return new Promise(async(resolve, reject)=>{
            let gameInfoList = await redisBase.getGameListZt();
            if(gameInfoList){
                for (let i = 0; i < gameInfoList.length; i++) {
                    // log.info('===========updateUserScore ==============',1,gameInfoList[i]);
                    let cfg = JSON.parse(gameInfoList[i]);
                    if(cfg.uid === uid && cfg.gamType === gameType){
                        cfg.score += score;
                        log.info('========updateUserScore========',cfg.score);
                        let res = await redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
                        if(res){
                            resolve(cfg);
                        }else{
                            reject(null);
                        }
                        break;
                    }
                }
            }
        })
    }

    //添加晋级
    async addJj(gameInfo,gameType){
        //当前我的等级和勋章数据
        let dwLv = gameInfo.dwLv;
        let dwXzNum = gameInfo.dwXzNum;
        let dwType = gameInfo.dwType;

        if(dwType === 0){
            dwType = 1; //默认段位等级就是1
        }

        let cfg = gameZtCfg.dwlvCfg[dwType];
        if(dwLv + 1 >= cfg.lvMin && dwLv + 1 <= cfg.lvMax){ //单纯的晋级不晋段位
            return 1;
        }else{ //晋级且晋段位
            //这个使用需要给段位结算
            return 2;
        }
        return 0;
    }


    更新段位等级
    updateDwType(lv){
        let cfg = gameZtCfg.dwlvCfg;
        let dwType = 1;
        for (const key in cfg) {
            let tmp = cfg[key];
            if(lv >= tmp.lvMin && lv <= tmp.lvMax){
                dwType = tmp.dwType;
                break;
            }
        }
        return dwType;
    }

    /**
     * 结算根据输赢更新勋章和等级
     * @param uid
     * @param gameType
     * @param isWin 0 是输 1 是赢了
     */
    async updateUserXZAndLv(uid,gameType, isWin){
        log.info('=======updateUserXZAndLv============',uid,gameType,isWin);
        let gameInfoList = await redisBase.getGameListZt();
        if(gameInfoList){
            log.info('========updateUserXZAndLv=========',gameInfoList.length);
            for (let i = 0; i < gameInfoList.length; i++) {
                log.info('===========updateUserScore ==============',i);
                let cfg = JSON.parse(gameInfoList[i]);

                let isReward = false;
                if(cfg.uid === uid && cfg.gamType === gameType){
                    let dwLv = cfg.dwLv;
                    let dwType = cfg.dwType === 0 ? 1 : cfg.dwType;//默认段位等级就是1
                    //该玩家赢了
                    if(isWin === 1){
                        log.warn(`===用户 ${cfg.name} 赢了===`);
                        cfg.dwXzNum += 1;
                        cfg.xzNumCost += 1;
                        //判断是否可以晋级
                        let cfgZt = gameZtCfg.dwlvCfg[dwType];
                        if(cfg.dwXzNum >= cfgZt.costXz){
                            if(dwLv + 1 >= cfgZt.lvMin && dwLv + 1 <= cfgZt.lvMax){ //单纯的晋级不晋段位
                                log.info('=========单纯的晋级不晋段位=======')
                                cfg.dwLv++;
                                cfg.dwXzNum = cfg.dwXzNum - cfgZt.costXz;
                                isReward = true;
                                await redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
                            }else {
                                //晋级且晋段位      //这个使用需要给段位结算
                                cfgZt = gameZtCfg.dwlvCfg[dwType+1];
                                log.info('=========晋级且晋段位=======')
                                if(cfg.dwXzNum >= cfgZt.costXz){
                                    cfg.dwLv++;
                                    cfg.dwXzNum = cfg.dwXzNum - cfgZt.costXz;
                                    isReward = true;
                                    await  redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
                                }
                            }
                        }
                    }else if(isWin === 0){//该玩家输了
                        log.warn(`===用户 ${cfg.name} 输了===`);
                        if(cfg.dwXzNum > 0){
                            cfg.dwXzNum -= 1;
                        }
                        if(cfg.xzNumCost > 0) {
                            cfg.xzNumCost -= 1;
                        }
                    }
                    log.error('=========updateDwLv1===========',cfg.xzNumCost);
                    let res =  AlgorZt.updateDwLv(cfg.xzNumCost);
                    log.error('=========updateDwLv2===========',res);

                    log.error('=========updateDwLv3===========',cfg.dwLv,res.lv);
                    if(isReward){
                        log.error('========有段位奖励=========')
                        cfg.dwLv = res.lv;
                        cfg.dwType = res.dwType;

                        setTimeout(()=>{
                            this.broadDwGameEnd(cfg.roomId,cfg);
                        },500)
                    }
                    await redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
                    break;
                }
            }
        }
    }

    broadDwGameEnd(roomId, reward){
        log.info('==========broadDwGameEnd============',roomId,reward);

        let ret = {
            rewardType: gameCfg.RewardType.TYpe_QiuNum,
            rewardNum: reward,
            dwLv: number,   //段位等级
            dwType: number, //段位类型
            gameType: number, //主题赛类型
        }
    }

    //记录答对的题目数
     async recordAnswerTrue(uid,tid){
        // return new Promise(async(resolve, reject)=>{
            let list = await global.gameSerMgr.gameRedis.get_redis_topic_list(uid);
            if(list){
                if(list.indexOf(tid) === -1){
                    await global.gameSerMgr.gameRedis.push_topic_to_list(uid,tid);
                }
            }
            // resolve();
        // })
    }


    //断线亲空玩家对应的房间信息
    async theme_match_discannect_clear_roomInfo(uid) {
        let roomList = await redisBase.getValidRoomInList();
        if(roomList){
            for (let i = 0; i < roomList.length; i++) {
                let cfg = JSON.parse(roomList[i]);
                let gameType = cfg.gameTypeZt;
                let idx = cfg.players.indexOf(uid);
                if (idx !== -1) { //表示我存在
                    if (idx === 0) { //我创建的房间
                        //移除房间信息
                        await redisBase.delRooomList(i, JSON.stringify(cfg));
                        //移除自己
                        this.removeFromGameInfoList(gameType, uid);
                        //移除其他人
                        let uid2 = cfg.players[1];
                        if (uid2) {
                            this.removeFromGameInfoList(gameType, uid2);
                        }
                    } else if (idx === 1) { //我加入的房间
                        //从当前房间移除自己
                        cfg.players[idx] = null;
                        //移除自己
                        this.removeFromGameInfoList(gameType, uid);
                        //更新房间信息
                        log.info('======更新房间信息=====',cfg)
                        await redisBase.updateRoomListValue(i, JSON.stringify(cfg))
                    }
                    break;
                }
            }
        }else {
            log.error('===theme_match_discannect_clear_roomInfo=catch==', e);
        }
    }

    /**
     * 从列表 gameInfo_list_zt 里面移除 房间信息
     * @param gameType 主题类型 1文体 2足球 3民族
     * @param uid
     */
    async removeFromGameInfoList(gameType,uid){
        // let gamelist = await redisBase.getGameListZt();
        // if(gamelist){
        //     for (let i = 0; i < gamelist.length; i++) {
        //         let cfg =  JSON.parse(gamelist[i]);
        //         if(cfg.uid === uid && cfg.gamType === gameType){
        //             cfg.roomId = 0;
        //             await redisBase.updateGameListTzValue(i,JSON.stringify(cfg));
        //             break;
        //         }
        //     }
        // }else{
        //     log.error('===removeFromGameInfoList=catch==');
        // }
    }
}

module.exports = GameZtModel.getInstance();